import type { App } from 'vue'
/**
 * display flex 左右结构的div，添加一个拖动功能，调整左右的宽度
 */
export function dividerSlide(app: App) {
  // 单个权限验证（v-divider-slide）
  app.directive('dividerSlide', {
    mounted(el) {
      const hasClass = el.classList.contains('flex-divider-slide')
      if (!hasClass) {
        el.classList.add('flex-divider-slide')
      }
      const container = el.parentElement // 获取父容器
      const leftPane = el.previousElementSibling // 获取左侧面板
      const rightPane = el.nextElementSibling // 获取右侧面板

      let isDragging = false

      // 鼠标按下事件
      el.addEventListener('mousedown', () => {
        isDragging = true
        document.body.style.userSelect = 'none' // 禁用文本选择
        leftPane.style.flex = 'unset'
        rightPane.style.flex = 'unset'
        document.addEventListener('mousemove', onMouseMove)
        document.addEventListener('mouseup', onMouseUp)
      })

      // 鼠标移动事件
      function onMouseMove(e: any) {
        if (!isDragging) return

        const containerRect = container.getBoundingClientRect()
        let offsetX = e.clientX - containerRect.left

        // 最小宽度限制
        const minWidth = 200 // 左侧面板最小宽度
        if (offsetX < minWidth) offsetX = minWidth

        // 最大宽度限制
        const maxWidth = containerRect.width - 100 // 右侧面板最小宽度
        if (offsetX > maxWidth) offsetX = maxWidth

        // 设置左侧和右侧的宽度
        leftPane.style.width = `${offsetX}px`
        rightPane.style.width = `${containerRect.width - offsetX - el.offsetWidth}px`
      }

      // 鼠标松开事件
      function onMouseUp(e: any) {
        isDragging = false
        document.body.style.userSelect = '' // 恢复文本选择
        document.removeEventListener('mousemove', onMouseMove)
        document.removeEventListener('mouseup', onMouseUp)

        const containerRect = container.getBoundingClientRect()
        const offsetX = e.clientX - containerRect.left
        setTimeout(() => {
          leftPane.style.width = 'unset'
          rightPane.style.width = 'unset'
          leftPane.style.flex = `0 0 ${offsetX}px`
          rightPane.style.flex = `1 1 auto`
        }, 200)
      }
    }
  })
}
